<template>
  <div class="video-container">
    <div class="header">
      <h2>视频管理</h2>
      <el-button type="primary" @click="showAddDialog">新增视频</el-button>
    </div>

    <el-table :data="videoList" style="width: 100%" v-loading="loading">
      <el-table-column prop="cover" label="封面" width="180">
        <template slot-scope="scope">
          <el-image 
            style="width: 150px; height: 100px"
            :src="scope.row.cover"
            fit="cover">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="title" align="center" label="标题"></el-table-column>
      <el-table-column prop="expert_name" align="center" label="发布专家"></el-table-column>
      <el-table-column label="视频" width="180">
        <template slot-scope="scope">
          <el-button type="text" @click="previewVideo(scope.row)">预览视频</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="like" label="点赞量" width="120"></el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="videoForm" :rules="rules" ref="videoForm" label-width="80px">
        <el-form-item label="选择专家" prop="zhuanjia">
                        <el-button type="primary" @click="showExpertSelector = true">请选择</el-button>
                        
                        <div class="zhuanjia-info" v-if="videoForm.expert && videoForm.expert.id">
                            <img :src="videoForm.expert.avatar" alt="">
                            {{ videoForm.expert.nickname }}
                        </div>
                    </el-form-item>   
        <el-form-item label="标题" prop="title">
          <el-input v-model="videoForm.title"></el-input>
        </el-form-item>
        <el-form-item label="点赞量" prop="like">
          <el-input v-model="videoForm.like"></el-input>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <ImgCutter v-on:cutDown="cutDown" :cutWidth="330" :cutHeight="300">
    <template #open>
    </template>
</ImgCutter>
          <!-- <el-upload
            class="upload-demo"
            name="image"
            action="https://api.zctj16888.com/admin/v1/image/ossUpload"
            :on-success="handleCoverUploadSuccess"
            :before-upload="beforeCoverUpload"
            :show-file-list="false">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload> -->
          <el-image 
            v-if="videoForm.cover"
            style="width: 330px; height: 300px; margin-top: 10px"
            :src="videoForm.cover"
            fit="cover">
          </el-image>
        </el-form-item>
        <el-form-item label="视频" prop="url">
          <el-upload
            class="upload-demo"
            name="file"
            
            action="https://api.zctj16888.com/admin/v1/image/videosFile"
            :on-success="handleVideoUploadSuccess"
            :on-error="handleVideoUploadError"
            :before-upload="beforeVideoUpload"
            :show-file-list="false">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持mp4格式，且不超过100MB</div>
          </el-upload>
          <video 
            v-if="videoForm.url"
            style="width: 200px; margin-top: 10px"
            :src="videoForm.url"
            controls>
          </video>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 视频预览对话框 -->
    <el-dialog title="视频预览" :visible.sync="previewVisible" width="800px">
      <video 
        style="width: 100%"
        :src="previewVideoUrl"
        controls
        autoplay>
      </video>
    </el-dialog>
    <ExpertSelector
  :visible.sync="showExpertSelector"
  @select="handleExpertSelect"
/>
  </div>
</template>

<script>
import { getVideoList , setVideo , deleteVideo } from '@/api/video'
import ExpertSelector from '@/components/ExpertSelector.vue';
import ImgCutter from 'vue-img-cutter';
import axios from "axios";
import { Loading } from 'element-ui';
export default {
  name: 'VideoManagement',
  data() {
    return {
      loading: false,
      videoList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '新增视频',
      previewVisible: false,
      previewVideoUrl: '',
      videoForm: {
        id: '',
        title: '',
        cover: '',
        url: '',
        like: 0,
        expert: {}
      },
      showExpertSelector: false,
      rules: {
        title: [
          { required: true, message: '请输入视频标题', trigger: 'blur' }
        ],
        cover: [
          { required: true, message: '请上传视频封面', trigger: 'change' }
        ],
        src: [
          { required: true, message: '请上传视频文件', trigger: 'change' }
        ],
        like: [
          { required: true, message: '请填写点赞量', trigger: 'change' }

        ]
      },
      loadingInstance: null
    }
  },
  components: {
    ExpertSelector,
    ImgCutter

  },
  created() {
    this.fetchVideoList()
  },
  methods: {
    async cutDown(v) { 
      const formData = new FormData();
      // 添加文件到表单数据
      formData.append('image', v.file);

      try {
        const response = await axios.post('https://api.zctj16888.com/admin/v1/image/ossUpload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        // 上传成功后更新表单中的封面地址
        console.log(response)
        this.videoForm.cover = response.data.data.url;
        this.$message.success('封面上传成功');
      } catch (error) {
        console.error('封面上传失败', error);
        this.$message.error('封面上传失败，请重试');
      }
    },
    handleExpertSelect(v) {
            this.videoForm.expert = v;
           
        },
    async fetchVideoList() {
      this.loading = true
      try {
        const response = await getVideoList({
          page: this.currentPage,
          pageSize: this.pageSize
        })
        this.videoList = response.data.data
        this.total = response.data.total
      } catch (error) {
        this.$message.error('获取视频列表失败')
      } finally {
        this.loading = false
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchVideoList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchVideoList()
    },
    showAddDialog() {
      this.dialogTitle = '新增视频'
      this.videoForm = {
        id: '',
        title: '',
        cover: '',
        video: '',
        likes: 0
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑视频'
      this.videoForm = { ...row }
      this.dialogVisible = true
    },
    previewVideo(row) {
      this.previewVideoUrl = row.url
      this.previewVisible = true
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该视频吗？', '提示', {
          type: 'warning'
        })
        // 这里替换为实际的API调用
        
        await deleteVideo({
            id: row.id
        })
        this.$message.success('删除成功')
        this.fetchVideoList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    beforeCoverUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt500K = file.size / 1024 < 500

      if (!isImage) {
        this.$message.error('上传封面图片只能是 JPG/PNG 格式!')
      }
      if (!isLt500K) {
        this.$message.error('上传封面图片大小不能超过 500KB!')
      }
      return isImage && isLt500K
    },
    beforeVideoUpload(file) {
      this.loadingInstance = Loading.service({
        text: '视频上传压缩中'
      });
      const isVideo = file.type === 'video/mp4'
      const isLt100M = file.size / 1024 / 1024 < 100

      if (!isVideo) {
        this.$message.error('上传视频只能是 MP4 格式!')
        this.loadingInstance.close()
      }
      if (!isLt100M) {
        this.$message.error('上传视频大小不能超过 100MB!')
        this.loadingInstance.close()

      }

      

      return isVideo && isLt100M
    },
    handleCoverUploadSuccess(response) {
        this.$nextTick(() => {
      this.videoForm.cover = response.data.url

        })
    },
    handleVideoUploadError(error) {
      this.loadingInstance.close()
    },
    handleVideoUploadSuccess(response) {
        
        console.log(response);

        this.$nextTick(() => {

            this.videoForm.url = response.data.url
            this.$forceUpdate()
            this.loadingInstance.close()
        })

    },
    async submitForm() {
      this.$refs.videoForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.videoForm.id) {
              // 更新视频
              await setVideo({
                ...this.videoForm,
                expert_id: this.videoForm.expert.id
              })
            } else {
              // 新增视频

              
              await setVideo({
                ...this.videoForm,
                expert_id: this.videoForm.expert.id
              })
            }
            this.$message.success('保存成功')
            this.dialogVisible = false
            this.fetchVideoList()
          } catch (error) {
            console.log(error)
            this.$message.error('保存失败')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.video-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.upload-demo {
  margin-bottom: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.zhuanjia-info {
    display: flex;
    align-items: center;
    margin-top: 10px;
}
.zhuanjia-info>img {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-right: 10px;
}
</style>